<template>
  <div class="category-filter" ref="filterContainer">
    <!-- 0级 - 固定横向排列 -->
    <div class="level-0-container">
      <div class="item-container" v-for="(item, index) in level0Data" :key="item.id" :style="{height: (subIndex == index && showSubLevel) ? (subLevelHeight + 36) + 'px' : ''}">
        <div class="level-0-item" :class="{ active: activeIds[0] === item.id }" @click.stop="handleLevelClick(item, 0, index)"
          ref="level0Items">
          {{ item.standardName }}
        </div>
        <div v-if="subIndex == index && item.children && item.children.length > 0" ref="subLevelsContainer" class="sub-levels-container"  :style="subLevelPosition" >
          <div class="level-0-item" v-for="sub in item.children" :key="sub.id" :class="{ active: activeIds[1] === sub.id }" @click.stop="handleLevelClick(sub, 1, index)">{{sub.standardName}}</div>
          <div v-if="level2Data.length > 0" class="level-2-container">
            <div v-for="(sub, i) in level2Data" :key="i" class="level-2-item"
              :class="{ active: activeIds[2] === sub.id }" @click.stop="handleLevelClick(sub, 2,subIndex)">
              {{ sub.standardName }}
            </div>

            <div v-if="level3Data.length > 0" class="level-3-container">
              <div v-for="(sub, i) in level3Data" :key="i" class="level-3-item"
                :class="{ active: activeIds[3] === sub.id }" @click.stop="handleLevelClick(sub, 3,subIndex)">
                {{ sub.standardName }}
              </div>
            </div>
          </div>
        </div>

        <!-- <div v-if="showSubLevel" ref="subLevelsContainer" class="sub-levels-container" :style="subLevelPosition" @click.stop>

          <div v-if="level1Data.length > 0" class="level-1-container">
            <div v-for="(sub, i) in level1Data" :key="i" class="level-1-item"
              :class="{ active: activeIds[1] === sub.id }" @click.stop="handleLevelClick(sub, 1, subIndex)">
              {{ sub.standardName }}{{subIndex}}{{index}}
            </div>
          </div>


          <div v-if="level2Data.length > 0" class="level-2-container">
            <div v-for="(sub, i) in level2Data" :key="i" class="level-2-item"
              :class="{ active: activeIds[2] === sub.id }" @click.stop="handleLevelClick(sub, 2,subIndex)">
              {{ sub.standardName }}
            </div>
          </div>


          <div v-if="level3Data.length > 0" class="level-3-container">
            <div v-for="(sub, i) in level3Data" :key="i" class="level-3-item"
              :class="{ active: activeIds[3] === sub.id }" @click.stop="handleLevelClick(sub, 3,subIndex)">
              {{ sub.standardName }}
            </div>
          </div>
        </div> -->
      </div>
    </div>


  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, onUnmounted, ref } from "vue";

interface CategoryItem {
  id: string;
  standardName: string;
  pid: string;
  children?: CategoryItem[];
}

const props = defineProps<{
  data: CategoryItem[];
}>();

const emit = defineEmits<{
  (event: "update-selection", payload: { ids: string[] }): void;
}>();

// 当前选中的各级ID [0级, 1级, 2级, 3级]
const activeIds = ref<string[]>([]);
const level0Items = ref<HTMLElement[]>([]);
const subLevelPosition = ref({ left: '0'});
const filterContainer = ref<HTMLElement | null>(null);

const showSubLevel = computed(() => activeIds.value[0] && (level1Data.value.length > 0 || level2Data.value.length > 0 || level3Data.value.length > 0));
const subLevelsContainer = ref<HTMLElement[]>([]);
const subLevelHeight = ref(0);
const subIndex = ref(-1);

// 获取各级数据
const level0Data = computed(() => props.data);
const level1Data = computed(() =>
  activeIds.value[0]
    ? props.data.find(item => item.id === activeIds.value[0])?.children || []
    : []
);
const level2Data = computed(() =>
  activeIds.value[1]
    ? level1Data.value.find(item => item.id === activeIds.value[1])?.children || []
    : []
);
const level3Data = computed(() =>
  activeIds.value[2]
    ? level2Data.value.find(item => item.id === activeIds.value[2])?.children || []
    : []
);

// 处理点击事件



const handleLevelClick = async (item: CategoryItem, level: number, index: number) => {
      subIndex.value = index

  // 更新当前级别的选中ID
  activeIds.value[level] = item.id;
  console.log(activeIds.value)

  // 清空更高级别的选中状态
  for (let i = level + 1; i < 4; i++) {
    activeIds.value[i] = "";
  }

  // 更新子级容器位置
  if (level === 0) {
    await nextTick();
    updateSubLevelPosition();
  }

  // 获取最末级的选中ID
  const lastSelectedId = activeIds.value
    .slice() // 创建副本以避免直接操作原数组
    .reverse() // 反转数组以从后往前查找
    .find(id => id !== ""); // 找到第一个非空ID

  // 触发事件，仅传递最末级的选中ID
  emit("update-selection", {
    id: lastSelectedId || "" // 如果没有选中任何项，则传递空字符串
  });
  nextTick(() => {
    if (subLevelsContainer.value[0]) {
      const rect = subLevelsContainer.value[0].getBoundingClientRect();
      const containerRect = filterContainer.value?.getBoundingClientRect();
      const activeElement = level0Items.value[index];
      if (activeElement) {
        const activeRect = activeElement.getBoundingClientRect();
        if (rect && containerRect) {
          subLevelPosition.value = {
            left: containerRect.left - activeRect.left + 'px'
          };

        }
      }
      subLevelHeight.value = rect.height
      
    }
  })
};







// const handleLevelClick = async (item: CategoryItem, level: number) => {
//   // 更新当前级别的选中ID
//   activeIds.value[level] = item.id;

//   // 清空更高级别的选中状态
//   for (let i = level + 1; i < 4; i++) {
//     activeIds.value[i] = "";
//   }

//   // 更新子级容器位置
//   if (level === 0) {
//     await nextTick();
//     updateSubLevelPosition();
//   }

//   // 获取当前选中节点的完整路径信息
//   const selectedNode = getSelectedNode(item, level);

//   // 触发事件，传递选中节点的完整信息
//   emit("update-selection", { 
//     ids: activeIds.value.filter(id => id),
//     node: selectedNode
//   });
// };
// 辅助函数：获取当前选中节点的完整信息
const getSelectedNode = (item: CategoryItem, level: number): CategoryItem | null => {
  if (!item) return null;

  // 克隆当前节点，避免直接修改原始数据
  const node = { ...item };

  // 递归获取子节点信息
  if (level < 3 && node.children) {
    node.children = node.children.map(child => {
      if (child.id === activeIds.value[level + 1]) {
        return getSelectedNode(child, level + 1);
      }
      return child;
    }).filter(Boolean) as CategoryItem[];
  }

  return node;
};

// 更新子级容器位置
const updateSubLevelPosition = () => {
  if (!activeIds.value[0] || level0Items.value.length === 0) return;

  const activeIndex = level0Data.value.findIndex(item => item.id === activeIds.value[0]);
  if (activeIndex === -1) return;

  const activeElement = level0Items.value[activeIndex];
  if (!activeElement) return;


  const rect = activeElement.getBoundingClientRect();
  const containerRect = filterContainer.value?.getBoundingClientRect();


  // if (rect && containerRect) {
  //   subLevelPosition.value = {
  //     left: '0', // 靠左对齐
  //     top: `${rect.bottom - containerRect.top + 5}px`, // 显示在当前0级项的下方
  //     width: '100%' // 宽度与最外层同宽
  //   };
  // }
};
// 点击空白处关闭子级窗口
const handleClickOutside = (event: MouseEvent) => {
  subIndex.value = -1
  if (filterContainer.value && !filterContainer.value.contains(event.target as Node)) {
    activeIds.value = [];
    // emit("update-selection", { ids: [] });
  }
};

// 添加全局点击事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
  updateSubLevelPosition();
  console.log(props.data.length)
});

// 移除全局点击事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<style scoped>
.category-filter {
  /* width: 85%; */
  position: relative;


}

/* 0级容器 - 横向排列，超出换行 */
.level-0-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  position: relative;
}

.item-container {
  position: relative;
}

.level-0-item {
  padding: 4px 8px;
  /* border-radius: 16px;
    border: 1px solid #dcdfe6; */
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  color: #4e5969;
  white-space: nowrap;
  position: relative;
}

.level-0-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
  border-radius: 16px;
}

/* 1-3级容器 - 固定在当前选中的0级下方，靠左，宽度与最外层同宽 */
.sub-levels-container {
  position: absolute;
  z-index: 1000;
  padding: 12px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  width: 720px;
  top: 35px;
  display: flex;
  flex-wrap: wrap;
  /* gap: 10px; */
  /* left: 0; */
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
}

/* 各级样式 */
.level-1-container,
.level-2-container,
.level-3-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.level-1-item,
.level-2-item,
.level-3-item {
  padding: 4px 8px;
  /* border-radius: 16px;
    border: 1px solid #dcdfe6; */
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;

  color: #4e5969;
  white-space: nowrap;
}

.level-1-item.active,
.level-2-item.active,
.level-3-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
  border-radius: 16px;
}

/* 层级缩进 */
.level-2-container {
  margin-top: 10px;
  padding: 10px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  /* box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1); */
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.level-3-container {
  margin-top: 10px;
  padding: 10px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  /* box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1); */
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>
